package cn.willbj.brief.hootl.threads.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ExecutorsDemo01 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		Executors.newCachedThreadPool();
		
		Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
		
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), 100, 100, TimeUnit.MILLISECONDS, 
				new ArrayBlockingQueue<>(100), new ThreadFactory() {
					ThreadFactory defaultFactory = Executors.defaultThreadFactory();
					AtomicInteger atomicInteger = new AtomicInteger(1000);
					@Override
					public Thread newThread(Runnable r) {
						Thread newThread = defaultFactory.newThread(r);
						if (!newThread.isDaemon()) {
							newThread.setDaemon(true);
						}
						newThread.setName("will AsynTask "+atomicInteger.getAndIncrement());
						return newThread;
					}
				}, new ThreadPoolExecutor.CallerRunsPolicy());
		
		threadPoolExecutor.execute(new Runnable() {
			@Override
			public void run() {
				Thread currentThread = Thread.currentThread();
				System.out.println(currentThread.getName() + ":" +System.currentTimeMillis());
			}
		});
		
		Future<ArrayList<Object>> submit = threadPoolExecutor.submit(new Runnable() {
			@Override
			public void run() {
				Thread currentThread = Thread.currentThread();
				System.out.println(currentThread.getName() + ":" +System.currentTimeMillis());
			}
		}, new ArrayList<>());
		ArrayList<Object> arrayList = submit.get();
		System.out.println(arrayList);
		
		Future<List<String>> submit2 = threadPoolExecutor.submit(new Callable<List<String>>() {
			@Override
			public List<String> call() throws Exception {
				Thread currentThread = Thread.currentThread();
				System.out.println(currentThread.getName() + ":" +System.currentTimeMillis());
				List<String> arrayList2 = new ArrayList<>();
				arrayList2.add("xx");
				return arrayList2;
			}
		});
		List<String> list = submit2.get();
		System.out.println(list);
		
		String xString = "yy";
		Future<?> submit3 = threadPoolExecutor.submit(()-> {
			System.out.println(xString);
			return xString;
		});
		Object x = submit3.get();
		System.out.println(x);
	}
}
